import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { hasPagePermission, getUserRole, getPermissionMessage } from '../utils/permission';
import { Toast } from 'antd-mobile';

interface RouteGuardProps {
  children: React.ReactNode;
}

const RouteGuard: React.FC<RouteGuardProps> = ({ children }) => {
  const location = useLocation();
  const { pathname } = location;
  
  // 检查页面访问权限
  if (!hasPagePermission(pathname)) {
    const userRole = getUserRole();
    const restrictedFeatures = ['消息中心', '商城', '患者案例', '预约挂号', '复诊开方', '搜索功能'];
    
    // 根据路径确定被限制的功能名称
    let featureName = '该功能';
    if (pathname.includes('/message')) featureName = '消息中心';
    else if (pathname.includes('/shopping')) featureName = '商城';
    else if (pathname.includes('/anli')) featureName = '患者案例';
    else if (pathname.includes('/Yuyue')) featureName = '预约挂号';
    else if (pathname.includes('/Fuzhen')) featureName = '复诊开方';
    else if (pathname.includes('/Search')) featureName = '搜索功能';
    
    // 显示权限提示
    Toast.show({
      content: getPermissionMessage(featureName),
      duration: 3000
    });
    
    // 重定向到首页
    return <Navigate to="/index" replace />;
  }
  
  return <>{children}</>;
};

export default RouteGuard;
